import os
import re
import tkinter as tk
from tkinter import filedialog, scrolledtext, messagebox, ttk
from opencc import OpenCC
import chardet  # 用于检测文件编码


class SRTConverter:
    def __init__(self, root):
        self.root = root
        self.root.title("SRT字幕繁转简工具")
        self.root.geometry("900x400")
        self.root.resizable(True, True)

        # 设置中文字体支持
        self.font = ('SimHei', 10)

        # 创建OpenCC转换器实例
        self.converter = OpenCC('t2s')

        # 存储当前文件路径和编码
        self.file_path = None
        self.detected_encoding = "utf-8"

        # 常见编码列表
        self.common_encodings = [
            "utf-8", "gbk", "gb2312", "big5",
            "utf-16", "utf-16-le", "utf-16-be"
        ]

        # 创建UI组件
        self.create_widgets()

    def create_widgets(self):
        # 创建主框架
        main_frame = tk.Frame(self.root, padx=10, pady=10)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 创建按钮和编码选择框架
        control_frame = tk.Frame(main_frame)
        control_frame.pack(fill=tk.X, pady=(0, 10))

        # 按钮子框架
        button_frame = tk.Frame(control_frame)
        button_frame.pack(side=tk.LEFT)

        # 导入文件按钮
        self.import_btn = tk.Button(
            button_frame, text="导入SRT文件", command=self.import_file, font=self.font
        )
        self.import_btn.pack(side=tk.LEFT, padx=(0, 10))

        # 转换按钮
        self.convert_btn = tk.Button(
            button_frame, text="转换", command=self.convert_text, font=self.font
        )
        self.convert_btn.pack(side=tk.LEFT, padx=(0, 10))

        # 导出文件按钮
        self.export_btn = tk.Button(
            button_frame, text="导出结果", command=self.export_file, font=self.font
        )
        self.export_btn.pack(side=tk.LEFT)

        # 编码选择子框架
        encoding_frame = tk.Frame(control_frame)
        encoding_frame.pack(side=tk.RIGHT, padx=(10, 0))

        # 编码选择标签
        tk.Label(encoding_frame, text="文件编码:", font=self.font).pack(side=tk.LEFT)

        # 编码选择下拉框
        self.encoding_var = tk.StringVar(value="utf-8")
        self.encoding_combobox = ttk.Combobox(
            encoding_frame,
            textvariable=self.encoding_var,
            values=self.common_encodings,
            width=10,
            state="readonly"
        )
        self.encoding_combobox.pack(side=tk.LEFT)

        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(main_frame, variable=self.progress_var, maximum=100)
        self.progress_bar.pack(fill=tk.X, pady=(0, 10))

        # 创建标签框架 - 原始文本
        original_frame = tk.LabelFrame(main_frame, text="原始繁体字幕", font=self.font)
        original_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10), side=tk.LEFT)
        original_frame.pack_propagate(False)

        # 原始文本区域
        self.original_text = scrolledtext.ScrolledText(
            original_frame, wrap=tk.WORD, font=self.font
        )
        self.original_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 创建标签框架 - 转换后文本
        converted_frame = tk.LabelFrame(main_frame, text="转换后简体字幕", font=self.font)
        converted_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10), side=tk.RIGHT)
        converted_frame.pack_propagate(False)

        # 转换后文本区域
        self.converted_text = scrolledtext.ScrolledText(
            converted_frame, wrap=tk.WORD, font=self.font
        )
        self.converted_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 分割窗口
        original_frame.configure(width=450)
        converted_frame.configure(width=450)

    def detect_encoding(self, file_path):
        """检测文件编码"""
        try:
            # 读取文件的前10000字节用于检测编码
            with open(file_path, 'rb') as f:
                raw_data = f.read(10000)

            # 使用chardet检测编码
            result = chardet.detect(raw_data)
            encoding = result['encoding']

            # 如果检测到的编码不在常见编码列表中，使用utf-8
            if encoding and encoding.lower() in [e.lower() for e in self.common_encodings]:
                return encoding.lower()
            return "utf-8"
        except Exception as e:
            print(f"编码检测出错: {str(e)}")
            return "utf-8"

    def import_file(self):
        """导入SRT字幕文件，带编码检测"""
        file_path = filedialog.askopenfilename(
            title="选择SRT字幕文件",
            filetypes=[("SRT字幕文件", "*.srt"), ("所有文件", "*.*")]
        )

        if file_path:
            self.file_path = file_path
            # 检测文件编码
            detected_encoding = self.detect_encoding(file_path)
            self.detected_encoding = detected_encoding
            self.encoding_var.set(detected_encoding)

            try:
                # 使用检测到的编码读取文件
                with open(file_path, 'r', encoding=detected_encoding, errors='replace') as f:
                    content = f.read()

                self.original_text.delete(1.0, tk.END)
                self.original_text.insert(tk.END, content)
                self.root.title(f"SRT字幕繁转简工具 - {os.path.basename(file_path)}")

            except Exception as e:
                messagebox.showerror("错误", f"读取文件时出错:\n{str(e)}")

    def convert_text(self):
        """将繁体字幕转换为简体，保持SRT格式不变"""
        srt_content = self.original_text.get(1.0, tk.END)
        # 保留原始的结尾方式，不做rstrip处理
        original_end = srt_content[-1:] if srt_content else ''

        if not srt_content.strip():
            messagebox.showwarning("警告", "请先导入SRT字幕文件")
            return

        try:
            # 按行分割内容，保留空行
            lines = srt_content.split('\n')
            converted_lines = []
            total_lines = len(lines)

            for i, line in enumerate(lines):
                # 更新进度条
                self.progress_var.set((i / total_lines) * 100)
                self.root.update_idletasks()

                # 检查是否是序号行（纯数字）
                if re.match(r'^\d+$', line.strip()):
                    converted_lines.append(line)
                # 检查是否是时间轴行
                elif re.match(r'^\d+:\d+:\d+,\d+\s*-->\s*\d+:\d+:\d+,\d+$', line.strip()):
                    converted_lines.append(line)
                # 否则视为字幕内容，进行转换
                else:
                    if line.strip():  # 非空行才转换
                        converted_line = self.converter.convert(line)
                        converted_lines.append(converted_line)
                    else:
                        converted_lines.append(line)  # 保留空行

            # 合并转换后的行，使用原始的换行方式
            converted_content = '\n'.join(converted_lines)
            # 恢复原始的结尾字符
            if original_end and not converted_content.endswith(original_end):
                converted_content += original_end

            self.converted_text.delete(1.0, tk.END)
            self.converted_text.insert(tk.END, converted_content)

            # 完成后进度条设为100%
            self.progress_var.set(100)
            messagebox.showinfo("成功", "字幕转换完成")

        except Exception as e:
            messagebox.showerror("错误", f"转换时出错:\n{str(e)}")
            self.progress_var.set(0)

    def export_file(self):
        """导出转换后的字幕，使用UTF-8编码"""
        simplified_text = self.converted_text.get(1.0, tk.END)
        # 不做rstrip处理，保留原始格式

        if not simplified_text.strip():
            messagebox.showwarning("警告", "没有可导出的转换结果")
            return

        # 默认文件名：原文件名加"_simplified"后缀
        default_filename = "converted_simplified.srt"
        if self.file_path:
            name, ext = os.path.splitext(os.path.basename(self.file_path))
            default_filename = f"{name}_simplified{ext}"

        file_path = filedialog.asksaveasfilename(
            title="保存转换结果",
            defaultextension=".srt",
            initialfile=default_filename,
            filetypes=[("SRT字幕文件", "*.srt"), ("所有文件", "*.*")]
        )

        if file_path:
            try:
                # 始终使用UTF-8编码保存
                with open(file_path, 'w', encoding='utf-8', newline='') as f:
                    f.write(simplified_text)
                messagebox.showinfo("成功", f"转换结果已保存到:\n{os.path.abspath(file_path)}")
            except Exception as e:
                messagebox.showerror("错误", f"保存文件时出错:\n{str(e)}")


if __name__ == "__main__":
    root = tk.Tk()
    app = SRTConverter(root)
    root.mainloop()
